<?php

namespace app\api\controller;

use app\api\model\store\Shop as ShopModel;
use app\common\service\qrcode\Base;
use app\common\service\qrcode\Extract;
use Grafika\Color;
use Grafika\Grafika;

class Manba extends \think\Controller
{

    protected $wxapp_id = '';


    public function ceshi()
    {

        $stock = new \app\common\model\store\Shop();;


        print_r(collection($stock->manba())->toArray());
    }


    public function order()
    {

        $data = db('order')
            ->where('pay_type', 20)
            ->where('pay_status', 20)
            ->where('info', 0)->select();

//        foreach ($data as $k => $v) {
//
//
//            $user = db('user')->where('user_id', $v['user_id'])->find();
//            $dealer_user = db('dealer_user')->where('user_id', $user['user_id'])->find();
//            $dealer_user_order = db('dealer_order')
//                ->where('user_id', $v['user_id'])
//                ->where('order_id', $v['order_id'])->find();
//
//            if ($dealer_user['referee_id'] != 0) {
//                $user11 = db('user')->where('user_id', $dealer_user['referee_id'])->find();
//                if ($user11) {
//                    if ($user11['grade_id'] == 10003) {
//                        $user['user_id'] > 0 && \app\store\model\dealer\User::grantpoint($user11['user_id'], $dealer_user_order['user_money']);
//                    }
//                }
//
//            }
//            $order_goods = db('order_goods')
//                ->where('order_id', $v['order_id'])->select();
//
//            $v['goods'] = $order_goods;
////            $goods = db('goods')->where('goods_id', $order_goods['goods_id'])->find();
//            $new = new\app\api\model\dealer\Order();
//            $capital = $new->getCapitalByOrder($v);
////            print_r($capital);exit;
//            $user['shi_id'] > 0 && \app\store\model\dealer\User::grantMoney($user['shi_id'], $capital['first_money']);
//            $user['qu_id'] > 0 && \app\store\model\dealer\User::grantMoney($user['qu_id'], $capital['second_money']);
//
//
//        }
        response_lm(200, '');

    }


//    判断用户是否是核销员
    public function dechect()
    {
        $data = input();

        $delar = db('store_shop_clerk')
            ->where('user_id', $data['user_id'])
            ->where('is_delete', 0)->find();

        if ($delar) {

            response_lm(200, '');
        } else {
            response_lm(100, '');
        }


    }


//判断用户是否是核销商
    public function delar()
    {
        $data = input();

        $delar = db('dealer_user')->where('user_id', $data['user_id'])->find();

        if ($delar) {

            response_lm(200, '');
        } else {
            response_lm(100, '');
        }


    }

    //判断用户是否是核销员
    public function storeshopclerk()
    {
        $data = input();

        $delar = db('store_shop_clerk')
            ->where('user_id', $data['user_id'])
            ->where('is_delete', 0)->find();
//        $cat = db('category')
//            ->where('parent_id', 0)
//            ->where('name', 'like', '%活动%')
//            ->find();

        $array = db('category')
            ->where('type', 2)
            ->field('category_id')
            ->select();


        foreach ($array as $v) {
            $re[] = $v['category_id'];
        }


        if (!isset(input()['goods_id'])) {
            if (!$delar) {
                response_lm(100, '');
            }
        } else {
            $goods = db('goods')
                ->where('goods_id', input()['goods_id'])
                ->whereIn('category_id', $re)
                ->find();
            if (!$goods) {
                response_lm(200, '');
            }
            if (!$delar && $goods) {
                response_lm(100, '');
            }
        }


    }

    /**
     * 销售业绩接口
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function achievement()
    {
//type 1 是销售业绩 2 是促销业绩
        $manba = input();


        $user = db('user')
            ->where('user_id', $manba['user_id'])
            ->find();
        $ref = db('dealer_referee')
            ->where('dealer_id', $manba['user_id'])
            ->where('level', 'in', [1, 2])
            ->field('user_id')
            ->select();
        $array = [];
        foreach ($ref as $v) {
            $array[] = $v['user_id'];
        }

        $array[] = $manba['user_id'];

       
        $achievement = db('order')
            ->where('user_id', 'in', $array)
            ->where('pay_status', 20)
            ->where('FROM_UNIXTIME(pay_time,"%Y-%m")="' . $manba['date'] . '"')
            ->sum('achievement');

        if ($achievement > 0) {

            response_lm(200, '222', $achievement);
        } else {

            response_lm(200, '111', '0.00');
        }


//        $manba['user_id'] = 10004;
        $user = db('user')
            ->where('user_id', $manba['user_id'])
            ->find();
        if ($user['grade_id'] == 10004) {
            $shizon = $user['shizon_id'];
        }
        if ($user['grade_id'] == 10001) {
            $shi = $user['shi_id'];
        }
        if ($user['grade_id'] == 10002) {
            $qu = $user['qu_id'];
        }
        if ($manba['type'] == 1) {
            if (isset($shizon)) {
                $dealer_order = db('dealer_order')
//                    ->where('is_settled', 1)
                    ->where('shizon_id', $shizon)
                    ->where('FROM_UNIXTIME(create_time,"%Y-%m")="' . $manba['date'] . '"')
                    ->where('ca_id', 'neq', 10013)
                    ->select();

                $dealer_order1 = 0;
                foreach ($dealer_order as $k => $v) {

                    $prder = db('order')
                        ->where('order_id', $v['order_id'])
                        ->where('pay_status', 20)
                        ->find();
                    $dealer_order1 = $dealer_order1 + $prder['order_price'];
                }
                $dealer_order = $dealer_order1;

            }
            if (isset($shi)) {
                $dealer_order = db('dealer_order')
//                    ->where('is_settled', 1)
                    ->where('shi_id', $shi)
                    ->where('FROM_UNIXTIME(create_time,"%Y-%m")="' . $manba['date'] . '"')
                    ->where('ca_id', 'neq', 10013)
                    ->select();

                $dealer_order1 = 0;
                foreach ($dealer_order as $k => $v) {

                    $prder = db('order')
                        ->where('order_id', $v['order_id'])
                        ->where('pay_status', 20)
                        ->find();
                    $dealer_order1 = $dealer_order1 + $prder['order_price'];
                }
                $dealer_order = $dealer_order1;
            }
            if (isset($qu)) {
                $dealer_order = db('dealer_order')
//                    ->where('is_settled', 1)
                    ->where('qu_id', $qu)
                    ->where('FROM_UNIXTIME(create_time,"%Y-%m")="' . $manba['date'] . '"')
                    ->where('ca_id', 'neq', 10013)
                    ->select();
                $dealer_order1 = 0;
                foreach ($dealer_order as $k => $v) {

                    $prder = db('order')
                        ->where('order_id', $v['order_id'])
                        ->where('pay_status', 20)
                        ->find();
                    $dealer_order1 = $dealer_order1 + $prder['order_price'];
                }


//                    ->sum('order_price');
                $dealer_order = $dealer_order1;
            }
        } else {
            if (isset($shizon)) {
                $dealer_order = db('dealer_order')
//                    ->where('is_settled', 1)
                    ->where('shizon_id', $shizon)
                    ->where('FROM_UNIXTIME(create_time,"%Y-%m")="' . $manba['date'] . '"')
                    ->where('ca_id', 'eq', 10013)
                    ->select();
                $dealer_order1 = 0;
                foreach ($dealer_order as $k => $v) {

                    $prder = db('order')
                        ->where('order_id', $v['order_id'])
                        ->where('pay_status', 20)
                        ->find();
                    $dealer_order1 = $dealer_order1 + $prder['order_price'];
                }
                $dealer_order = $dealer_order1;


            }
            if (isset($shi)) {
                $dealer_order = db('dealer_order')
//                    ->where('is_settled', 1)
                    ->where('shi_id', $shi)
                    ->where('FROM_UNIXTIME(create_time,"%Y-%m")="' . $manba['date'] . '"')
                    ->where('ca_id', 'eq', 10013)
                    ->select();
                $dealer_order1 = 0;
                foreach ($dealer_order as $k => $v) {

                    $prder = db('order')
                        ->where('order_id', $v['order_id'])
                        ->where('pay_status', 20)
                        ->find();
                    $dealer_order1 = $dealer_order1 + $prder['order_price'];
                }
                $dealer_order = $dealer_order1;
            }
            if (isset($qu)) {
                $dealer_order = db('dealer_order')
//                    ->where('is_settled', 1)
                    ->where('qu_id', $qu)
                    ->where('FROM_UNIXTIME(create_time,"%Y-%m")="' . $manba['date'] . '"')
                    ->where('ca_id', 'eq', 10013)
                    ->select();
                $dealer_order1 = 0;
                foreach ($dealer_order as $k => $v) {

                    $prder = db('order')
                        ->where('order_id', $v['order_id'])
                        ->where('pay_status', 20)
                        ->find();
                    $dealer_order1 = $dealer_order1 + $prder['order_price'];
                }
                $dealer_order = $dealer_order1;
            }
        }

        if (isset($dealer_order)) {
            response_lm(200, '', $dealer_order);
        } else {
            response_lm(200, '', 0.00);
        }


    }

    /**
     * 申请门店接口
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function mendian()
    {
        $data = input();


        $region0 = db('region')
            ->where('name', $data['region0'])
            ->where('level', 1)
            ->find();

        $region1 = db('region')
            ->where('name', $data['region1'])
            ->where('level', 2)
            ->find();

        $region2 = db('region')
            ->where('name', $data['region2'])
            ->where('level', 3)
            ->find();

        $data['province_id'] = $region0['id'];
        $data['city_id'] = $region1['id'];
        $data['region_id'] = $region2['id'];
        $data['wxapp_id'] = 10001;
        $data['create_time'] = time();

        unset($data['region0']);
        unset($data['region1']);
        unset($data['region2']);
        $model = new ShopModel;
        $shop = $model->save($data);
        if ($shop) {

            response_lm(200, '');
        }


    }

    /**
     * 门店列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function store()
    {
        $data1 = input();


        $model = new ShopModel;
        $data = $model->where('status', 1)->select()->toArray();

        foreach ($data as $k => $vv) {

            $mi = Manba::distance($data1['latitude'], $data1['longitude'], $vv['latitude'], $vv['longitude']);
            $data[$k]['distance'] = $mi;
            $mii[] = $mi;
            $img = db('upload_file')->where('file_id', $vv['logo_image_id'])->find();
            $data[$k]['logo_image'] = 'https://kangbei.6sjs.com/uploads/' . $img['file_name'];
        }
        array_multisort($mii, SORT_ASC, $data);
        response_lm(200, '', $data);


    }

    /**
     * 计算两个经纬度之间的距离
     * $miles::英里
     */
    static function distance($lat1, $lng1, $lat2, $lng2, $miles = false, $digit = 2)
    {

        $pi80 = M_PI / 180;
        $lat1 *= $pi80;
        $lng1 *= $pi80;
        $lat2 *= $pi80;
        $lng2 *= $pi80;
        $r = 6372.797; // mean radius of Earth in km
        $dlat = $lat2 - $lat1;
        $dlng = $lng2 - $lng1;
        $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlng / 2) * sin($dlng / 2);
        $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
        $km = $r * $c;
        $distance = ($miles ? ($km * 0.621371192) : $km);
        $distance = round($distance, $digit);
        return $distance;

    }

    /**
     * 搜索门店
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function search()
    {
        $data1 = input();
        $data = input();
        $model = new ShopModel;
        $data = $model->where('shop_name', 'like', '%' . $data['name'] . '%')->select()->toArray();

        if (empty($data)) {

            response_lm(200, '', []);
        } else {
            foreach ($data as $k => $vv) {
                $mi = Manba::distance($data1['latitude'], $data1['longitude'], $vv['latitude'], $vv['longitude']);
                $data[$k]['distance'] = $mi;
                $mii[] = $mi;
                $img = db('upload_file')->where('file_id', $vv['logo_image_id'])->find();
                $data[$k]['logo_image'] = 'https://kangbei.6sjs.com/uploads/' . $img['file_name'];
            }
            array_multisort($mii, SORT_ASC, $data);
            response_lm(200, '', $data);
        }


    }

    /**
     * 预约
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function appointment()
    {

        $data = input();


        $user = db('user')->where('user_id', $data['user_id'])->find();
        $shop = db('store_shop')->where('shop_id', $data['shopid'])->find();
        $data['user_name'] = $user['nickName'];
        $data['shop_name'] = $shop['shop_name'];

        $csc = db('apply')->insert($data);


        if ($csc) {
            response_lm(200, '');
        }

    }

// 活动详情页

    public function acavt()
    {
        $data = input();
        $huo = db('activity')->where('id', $data['id'])->find();
        $huo['bei_img'] = explode(',', $huo['bei_img']);

        $list = db('avtivity_list')
            ->where('activity_id', $data['id'])->select()->toArray();


        foreach ($list as $k => $v) {

            $newMobile1 = substr($v['phone'], 0, 5) . '****' . substr($v['phone'], 9);
            $list[$k]['phone'] = $newMobile1;
            $list[$k]['create_time'] = date('m-d H:i');
        }
        $huo['num'] = count($list);
        $shuzu = [];
        if (count($list) < 8) {
            $shuzu = array_merge($list, $list);
            $shuzu = array_merge($shuzu, $shuzu);
            $shuzu = array_merge($shuzu, $shuzu);
        }
        $sh = array_chunk($shuzu, 4);
        $huo['shuzu'] = $sh;


        response_lm('200', '', $huo);

    }

//活动列表页
    public function acavtlist()
    {
        $manba = db('activity')->where('is_delete', 0)->select()->toArray();

        foreach ($manba as $kk => $vv) {
            if (strpos($vv['bei_img'], ',') !== false) {
                $manba[$kk]['bei_img'] = explode(',', $vv['bei_img']);
                $manba[$kk]['imgg'] = $manba[$kk]['bei_img'][0];
            } else {
                $manba[$kk]['imgg'] = $vv['bei_img'];
            }


        }


        response_lm('200', '', $manba);

    }

//报名接口
    public function activity()
    {
        $data = input();
        $acaerr = db('activity')
            ->where('id', $data['activity_id'])
            ->find();


        $aca = db('avtivity_list')
            ->where('activity_id', $data['activity_id'])
            ->group('user_id')->count();


        if ($aca >= $acaerr['num']) {
            response_lm(300, '活动人数已满');
        }


        $user = \app\api\model\User::get($data['user_id']);

        $t = db('avtivity_list')->insert([
            'user_id' => $data['user_id'],
            'phone' => $data['phone'],
            'plate' => $data['plate'],
            'activity_id' => $data['activity_id'],
            'user_name' => $user->nickName,
            'avatar' => $user->avatarUrl,
            'create_time' => time()

        ]);
        if ($t) {
            response_lm(200, '');

        }


    }


//    验证用户是否报名
    public function lis()
    {

        $data = input();
        $acaerr = db('avtivity_list')
            ->where('user_id', $data['user_id'])
            ->where('activity_id', $data['id'])
            ->find();

        if ($acaerr) {
            response_lm(200, '');
        } else {
            response_lm(100, '');
        }


    }

    public function searchlist()
    {
        $data = input();

        $manba = db('activity')
            ->where('title', 'like', '%' . $data['name'] . '%')
            ->select()->toArray();
        if (empty($manba)) {
            response_lm(200, '', []);
        } else {
            foreach ($manba as $kk => $vv) {
                if (strpos($vv['bei_img'], ',') !== false) {
                    $manba[$kk]['bei_img'] = explode(',', $vv['bei_img']);
                    $manba[$kk]['imgg'] = $manba[$kk]['bei_img'][0];
                } else {
                    $manba[$kk]['imgg'] = $vv['bei_img'];
                }
            }
        }
        response_lm('200', '', $manba);
    }

    public function ma()
    {

        $data = input();
        $this->wxapp_id = $data['wxapp_id'];
        $ex = new Base();
        $qrcode = $ex->saveQrcode(
            $this->wxapp_id,
            "id:{$data['id']},user_id:{$data['user_id']}",
            'pages/avact/index'
        );

        copy($qrcode, $this->getPosterPath());

        $url = $this->getPosterUrl1();
        $img = db('activity')->where('id', $data['id'])->find();
        $upl = db('upload_file')->where('file_id', $img['bei_img_id'])->find();
        $data11 = $this->haibao('./uploads/' . $upl['file_name'] . '', $url, $data['title']);
        response_lm(200, '', $data11);
//        return $ex::savePoster($qrcode);


    }

    /**
     * 二维码文件路径
     * @return string
     */
    private function getPosterPath()
    {
        // 保存路径
        $tempPath = WEB_PATH . "temp/{$this->wxapp_id}/";
        !is_dir($tempPath) && mkdir($tempPath, 0755, true);
        return $tempPath . $this->getPosterName();
    }

    /**
     * 二维码文件名称
     * @return string
     */
    private function getPosterName()
    {
        return 'extract_' . md5("43_34334") . '.png';
    }

    /**
     * 二维码url
     * @return string
     */
    private function getPosterUrl1()
    {
        return './temp/' . $this->wxapp_id . '/' . $this->getPosterName();
    }

    public function haibao($img, $qrcode, $title)
    {
        // 判断海报图文件存在则直接返回url
//        if (file_exists($this->getPosterPath())) {
//            return $this->getPosterUrl();
//        }
        // 小程序id
        $wxappId = $this->wxapp_id;
        // 商品海报背景图
        $backdrop = __DIR__ . '/resource/goods_bg.png';
        // 下载商品首图
//       $goodsUrl = $this->saveTempImage($wxappId, $this->goods['image'][0]['file_path'], 'goods');
        // 小程序码参数
//        $scene = "gid:{$this->goods['goods_id']},uid:" . ($this->user_id ?: '');
        // 下载小程序码
//        $qrcode = $this->saveQrcode($wxappId, $scene, $this->pages[$this->goodsType]);
        // 拼接海报图

        return $this->manba($backdrop, $img, $qrcode, $title);
    }

    public function manba($backdrop, $goodsUrl, $qrcode, $title)
    {
        // 实例化图像编辑器
        $editor = Grafika::createEditor(['Gd']);
        // 字体文件路径
        $fontPath = Grafika::fontsDir() . '/' . 'st-heiti-light.ttc';
        // 打开海报背景图
        $editor->open($backdropImage, $backdrop);

        // 打开商品图片
        $editor->open($goodsImage, $goodsUrl);
        // 重设商品图片宽高
        $editor->resizeExact($goodsImage, 690, 690);
        // 商品图片添加到背景图
        $editor->blend($backdropImage, $goodsImage, 'normal', 1.0, 'top-left', 30, 30);
        // 商品名称处理换行
        $fontSize = 30;
        $goodsName = $this->wrapText($fontSize, 0, $fontPath, $title, 680, 2);
        // 写入商品名称
        $editor->text($backdropImage, $goodsName, $fontSize, 30, 750, new Color('#333333'), $fontPath);
        // 写入商品价格
        $priceType = [10 => 'goods_price', 20 => 'sharing_price'];
//        $editor->text($backdropImage, $this->goods['sku'][0][$priceType[$this->goodsType]], 38, 62, 964, new Color('#ff4444'));
        // 打开小程序码
        $editor->open($qrcodeImage, $qrcode);
        // 重设小程序码宽高
        $editor->resizeExact($qrcodeImage, 140, 140);
        // 小程序码添加到背景图
        $editor->blend($backdropImage, $qrcodeImage, 'normal', 1.0, 'top-left', 570, 914);
        // 保存图片
        $editor->save($backdropImage, $this->getPosterPath());

        return $this->getPosterUrl();
    }

    /**
     * 处理文字超出长度自动换行
     * @param integer $fontsize 字体大小
     * @param integer $angle 角度
     * @param string $fontface 字体名称
     * @param string $string 字符串
     * @param integer $width 预设宽度
     * @param null $max_line 最多行数
     * @return string
     */
    private function wrapText($fontsize, $angle, $fontface, $string, $width, $max_line = null)
    {
        // 这几个变量分别是 字体大小, 角度, 字体名称, 字符串, 预设宽度
        $content = "";
        // 将字符串拆分成一个个单字 保存到数组 letter 中
        $letter = [];
        for ($i = 0; $i < mb_strlen($string, 'UTF-8'); $i++) {
            $letter[] = mb_substr($string, $i, 1, 'UTF-8');
        }
        $line_count = 0;
        foreach ($letter as $l) {
            $testbox = imagettfbbox($fontsize, $angle, $fontface, $content . ' ' . $l);
            // 判断拼接后的字符串是否超过预设的宽度
            if (($testbox[2] > $width) && ($content !== "")) {
                $line_count++;
                if ($max_line && $line_count >= $max_line) {
                    $content = mb_substr($content, 0, -1, 'UTF-8') . "...";
                    break;
                }
                $content .= "\n";
            }
            $content .= $l;
        }
        return $content;
    }

    /**
     * 二维码url
     * @return string
     */
    private function getPosterUrl()
    {
        return \base_url() . 'temp/' . $this->wxapp_id . '/' . $this->getPosterName() . '?t=' . time();
    }
}